package com.etung.iot.demo.configs;


import com.etung.iot.demo.handler.Handler;
import com.etung.iot.demo.handler.HandlerFactory;
import com.etung.iot.demo.handler.TopicHandler;
import com.etung.iot.demo.storage.Storage;
import com.etung.iot.demo.storage.StorageFactory;
import com.etung.iot.demo.storage.StorageHandler;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.stereotype.Component;

@Component
public class HandlerRegisterConfig implements BeanPostProcessor {
    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        if (bean instanceof TopicHandler) {
            Class<?> cls = bean.getClass();
            Handler annotation = (Handler) cls.getAnnotation(Handler.class);
            if (annotation != null) {
                HandlerFactory.registerHandler(annotation.value(), (TopicHandler) bean);
            }
        }else if(bean instanceof StorageHandler){
            Class<?> cls = bean.getClass();
            Storage storageAnnotation = (Storage)cls.getAnnotation(Storage.class);
            if(storageAnnotation != null) {
                StorageFactory.registerHandler(storageAnnotation.value(), (StorageHandler) bean);
            }
        }
        return bean;
    }
}
